/**
 * 
 */
package com.gr.staffpm.user.changepassword;

import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.joda.time.Instant;

import com.gr.staffpm.datatypes.User;
import com.gr.staffpm.form.validation.PasswordInputValidator;
import com.gr.staffpm.model.StringModel;
import com.gr.staffpm.pages.behaviour.FocusOnLoadBehavior;
import com.gr.staffpm.security.service.UserService;


/**
 * @author Graham Rhodes 5 Mar 2011 00:08:05
 */
public class ChangePasswordPanel extends Panel {

    private static final long serialVersionUID = 1L;
    private final PasswordTextField pass;
    private final PasswordTextField passConf;

    public ChangePasswordPanel(String id, final UserService userService, final User user, final ModalWindow changePasswordWndw) {
        super(id);

        Form<User> form = new Form<User>("changePswdForm", new CompoundPropertyModel<User>(user));
        add(form);

        pass = new PasswordTextField("pass", new StringModel(user.getPassword()));
        pass.add(new FocusOnLoadBehavior());
        pass.setResetPassword(false);
        pass.setRequired(true);
        form.add(pass);

        passConf = new PasswordTextField("passConf", new StringModel(user.getPassword()));
        passConf.setResetPassword(false);
        passConf.setRequired(true);
        form.add(passConf);

        form.add(new PasswordInputValidator(pass, passConf));

        form.add(new AjaxButton("savePassButton") {

            private static final long serialVersionUID = 1L;

            @Override
            protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
                User currUser = userService.getCurrentUser();

                user.setPassword(new Sha256Hash(pass.getValue(), null, 1024).toBase64());
                user.setLastUpdated(new Instant().toDate());
                user.setUpdatedBy(currUser);

                userService.addOrUpdateUser(user);

                changePasswordWndw.close(target);
            }

        });

        AjaxButton cancel = new AjaxButton("cancelPassButton") {

            private static final long serialVersionUID = 1L;

            @Override
            protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
                changePasswordWndw.close(target);
            }

        };
        cancel.setDefaultFormProcessing(false);
        form.add(cancel);
    }

}
